package com.runa.monitor.platinterface.netservice.equipment.dtu.point;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.Point;
import com.runa.persistence.CollectionUtil;
import com.runa.protocol.dto.ModbusPoint;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.enums.ModbusDataType;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;


/**
 * 2024/9/2 13:43
 * zhangYB
 */
@Slf4j
public class ModbusPoints extends Points {

    private List<ModbusPoint> modbusPoints = new ArrayList<>();

    protected List<List<ModbusPoint>> sections = new ArrayList<>();

    public ModbusPoints(Integer limit) {
        super(limit);
    }

    public ModbusPoints() {

    }

    public static void main(String[] args) {
        JunPeiPoints junPeiPoints = new JunPeiPoints();
        List<List<ModbusPoint>> sections1 = junPeiPoints.getSections();
        System.out.println(JSON.toJSONString(sections1));
    }

    public List<ModbusPoint> getModbusPoints() {
        return modbusPoints;
    }

    public List<List<ModbusPoint>> getSections() {
        if (CollectionUtil.isNotEmpty(sections)) {
            return sections;
        }
        List<ModbusPoint> modbusPointList = getModbusPointList();
        ModbusPoint start = modbusPointList.get(0);
        int count = 0;
        List<ModbusPoint> section = new ArrayList<>();
        sections.add(section);
        for (ModbusPoint modbusPoint : modbusPointList) {
            int num = modbusPoint.getRegisterAddress() + modbusPoint.getRegisterCount() - start.getRegisterAddress();
            if (count + num > limit) {
                start = modbusPoint;
                count = 0;
                section = new ArrayList<>();
                section.add(modbusPoint);
                sections.add(section);
            } else {
                section.add(modbusPoint);
            }
        }
        return sections;
    }

    public List<ModbusPoint> getModbusPointList() {
        if (CollectionUtil.isNotEmpty(modbusPoints)) {
            return modbusPoints;
        }
        for (int i = 0; i < points.size(); i++) {
            try {
                Point point = points.get(i);
                ModbusPoint modbusPoint = new ModbusPoint(point.getId(), point.getCode(), ModbusDataType.valuesOf(point.getDataType()),
                        Integer.valueOf(point.getAddress()), ByteOrder.valueOf(point.getByteOrder()), point.getOffset());
                modbusPoints.add(modbusPoint);
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return modbusPoints;
    }

}
